package com.dmall.sso.service.impl;

import com.dmall.framework.result.DmallResult;
import com.dmall.sso.mapper.UserMapper;
import com.dmall.sso.pojo.TbUser;
import com.dmall.sso.service.RegisterService;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * 注册服务实现类
 * @author Chen 2017/11/16
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 校验数据
     * @param param 要校验的数据
     * @param type 校验的数据类型1.用户名 2.手机号 3.邮箱
     * @return
     */
    @Override
    public DmallResult checkData(String param, int type) {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        Example example = new Example(TbUser.class);
        Example.Criteria criteria= example.createCriteria();
        if(type ==1){
            criteria.andEqualTo("username",param);
        }else if(type ==2){
            criteria.andEqualTo("phone",param);
        }else if(type ==3){
            criteria.andEqualTo("email",param);
        }else {
            return DmallResult.build(400,"数据类型错误");
        }
        List<TbUser> list = mapper.selectByExample(example);
        if(list !=null && list.size() >0){
            return DmallResult.ok(false);
        }
        return DmallResult.ok(true);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @Override
    public DmallResult register(TbUser user) {
        //数据有效性校验
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())
                || StringUtils.isBlank(user.getPhone())) {
            return DmallResult.build(400, "用户数据不完整，注册失败");
        }
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        //1：用户名 2：手机号 3：邮箱
        DmallResult result = this.checkData(user.getUsername(), 1);
        if (!(boolean) result.getData()) {
            return DmallResult.build(400, "此用户名已经被占用");
        }
        result = checkData(user.getPhone(), 2);
        if (!(boolean)result.getData()) {
            return DmallResult.build(400, "手机号已经被占用");
        }
        //补全pojo的属性
        user.setCreated(new Date());
        user.setUpdated(new Date());
        //对密码进行md5加密
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        //把用户数据插入到数据库中
        mapper.insert(user);
        //返回添加成功
        return DmallResult.ok();
    }
}
